//
//  SearchViewController.m
//  ShouYi
//
//  Created by yrapp on 16/2/23.
//  Copyright © 2016年 yurui. All rights reserved.
//

#import "SearchViewController.h"
#import "searchHeaderView.h"
#import "SearchListViewController.h"
@interface SearchViewController ()<UISearchBarDelegate,UITableViewDataSource,UITableViewDelegate,UIScrollViewDelegate>
@property (nonatomic,strong)searchHeaderView *headerView;
@property (nonatomic,strong)UITableView *tableView;
@property (nonatomic,strong)NSMutableArray *recordArray;
@end

@implementation SearchViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    [self addHeaderView];
    // Do any additional setup after loading the view.
    
    
    NSString *filePath = [[self documentsPath] stringByAppendingPathComponent:@"/record.txt"];
    NSArray *array = [NSArray arrayWithContentsOfFile:filePath];
    [self.recordArray addObject:@"历史搜索"];
    [self.recordArray addObjectsFromArray:array];
    
    //添加tableView 搜索历史记录
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, kWidth, kHeight - 64) style:(UITableViewStylePlain)];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];

    
    
}

- (void)addHeaderView {
    
    self.headerView = [[searchHeaderView alloc] initWithFrame:CGRectMake(0, 0, kWidth, 64)];
    [self.headerView.backButton addTarget:self action:@selector(back) forControlEvents:(UIControlEventTouchUpInside)];
    self.headerView.searchBar.delegate = self;
    self.headerView.backgroundColor = kBackGroundColor;
    [self.view addSubview:self.headerView];
    
}

//沙盒document地址
- (NSString *)documentsPath {
    NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
    return docPath;
}


- (void)back {
    
    [self.navigationController popViewControllerAnimated:YES];
    
}


- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    
    [self.headerView.searchBar endEditing:YES];
    
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


//调用键盘搜索功能
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    
    NSString *filePath = [[self documentsPath] stringByAppendingPathComponent:@"/record.txt"];
    
    if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
        NSMutableArray *array = [NSMutableArray arrayWithContentsOfFile:filePath];
        
        int exist = 0;
        
        for (NSString *items in array) {
            if ([items isEqualToString:searchBar.text]) {
                ++exist;
            }
        }
        
        if (exist == 0) {
            [array insertObject:searchBar.text atIndex:0];
        }
        
        [array writeToFile:filePath atomically:YES];
        
    }else {
        
        NSMutableArray *array = [NSMutableArray arrayWithObjects:searchBar.text, nil];
        [array writeToFile:filePath atomically:YES];
        
    }
    
    NSLog(@"   %@",filePath);
    
    [self.headerView.searchBar resignFirstResponder];
    
    self.hidesBottomBarWhenPushed=YES;
    
    SearchListViewController *searchListVC = [[SearchListViewController alloc] init];
    
    searchListVC.keyname = searchBar.text;
    
    [self.navigationController pushViewController:searchListVC animated:YES];

//    self.hidesBottomBarWhenPushed=NO;
    
}

////搜索框内容监控 (输入框不为0 搜索按钮变白色)
//- (BOOL)searchBar:(UISearchBar *)searchBar shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
//    
//    if (range.location > 0 || text.length > 0) {
//        [self.headerView.searchButton setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
//    }else {
//        [self.headerView.searchButton setTitleColor:[UIColor grayColor] forState:(UIControlStateNormal)];
//    }
//    
//    return YES;
//}


#pragma mark --- 懒加载 ---
// 搜索历史记录 数组
- (NSMutableArray *)recordArray {
    
    if (!_recordArray) {
        _recordArray = [NSMutableArray array];
    }
    return _recordArray;
    
    
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return _recordArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    
    if (indexPath.row == 0) {
        cell.textLabel.textColor = [UIColor grayColor];
    }
    cell.textLabel.text = _recordArray[indexPath.row];
    cell.textLabel.font = [UIFont systemFontOfSize:14.0];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [self.headerView.searchBar resignFirstResponder];
    
    self.hidesBottomBarWhenPushed=YES;
//    
    SearchListViewController *searchListVC = [[SearchListViewController alloc] init];
    searchListVC.keyname = self.recordArray[indexPath.row];
    [self.navigationController pushViewController:searchListVC animated:YES];
//    self.hidesBottomBarWhenPushed=NO;
    
}

//拖动屏幕 回收键盘
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    [self.headerView.searchBar resignFirstResponder];
}

#pragma mark --- 表尾 ---
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 40;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kWidth, 40)];
    UIButton *deleButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
    deleButton.frame = CGRectMake((kWidth - 100) / 2, 5, 100, 30);
    [deleButton setTitle:@"清除搜索历史" forState:(UIControlStateNormal)];
    [deleButton setTitleColor:[UIColor redColor] forState:(UIControlStateNormal)];
    deleButton.titleLabel.font = [UIFont systemFontOfSize: 14.0];
    
    [deleButton addTarget:self action:@selector(deleRecord) forControlEvents:(UIControlEventTouchUpInside)];
    
    deleButton.layer.borderColor = [UIColor redColor].CGColor;
    deleButton.layer.cornerRadius = 5;
    deleButton.layer.borderWidth = 1;
    [view addSubview:deleButton];
    
    return view;
}

- (void)deleRecord {
    _recordArray = nil;
    [self.recordArray addObject:@"历史搜索"];
    
    NSString *filePath = [[self documentsPath] stringByAppendingPathComponent:@"/record.txt"];
    
    [[NSFileManager defaultManager] removeItemAtPath:filePath error:nil];
    
    [self.tableView reloadData];
    
}



/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
